import datetime
import time

import jwt
from xm3.settings import SECRET_KEY

header = {
    'alg': 'HS256',  # 加密算法
    'typ': 'JWT'  # 令牌类型
}

class JWTAuthentication:
    def authenticate(self, request):
        auth_header = request.META.get('HTTP_AUTHORIZATION', '').split()
        if len(auth_header) != 2 or auth_header[0].lower() != 'bearer':
            return None

        try:
            token = auth_header[1]
            payload = MyJWT().gettoken(token)
            user = models.Users.objects.get(id=payload['userid'])
            return (user, None)
        except Exception as e:
            return None

class MyJWT:
    def __init__(self):
        self.key = SECRET_KEY

    def settoken(self, user):
        payload = {
            'userid': user.get("userid"),
            "username": user.get("username", ""),  # 如果没有username，默认为空字符串
            "userphone": user.get("userphone", ""),  # 存储多少个数据 无所阿伟  但是一定要有过期时间
            "exp": user.get("exp")  # 过期时间
        }
        # 生成token
        return 'bearer ' + jwt.encode(payload, SECRET_KEY, algorithm="HS256", headers=header)

    # 验证token
    def gettoken(self, token):
        payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"], headers=header)
        return payload


mytoken = MyJWT()
# token='bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiXHU5NjhmXHU2Y2UyXHU5MDEwXHU2ZDQxIiwidXNlcnBob25lIjoiMTUzMjc0Mzc2NDIiLCJleHAiOjE3NDA2MDQ0NjB9.p2hAsiFmkWpftPZSltQ09EoYHxfcg6Wj0ugg9pEj3dk'
# token='bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjEsInVzZXJuYW1lIjoiXHU5NjhmXHU2Y2UyXHU5MDEwXHU2ZDQxIiwidXNlcnBob25lIjoiMTUzMjc0Mzc2NDIiLCJleHAiOjE3NDA2NTgxMjV9.tZ6KYQ878P1COGTRpFAapSbb6qxI09IJIkKzov_NqSQ'
# token1=token.split(' ')[1]
# print(mytoken.gettoken(token1))
# print(time.time())
# print(mytoken.gettoken(token1)['exp'])
# print(mytoken.gettoken(token1)['exp'] - time.time())